import serve from "@/api/login";
import Vue from "vue";
import store from "@/store";

const user = {
  state: {
    roles: [],
    sidebar: []
  },

  mutations: {
    SET_ROLES: (state, roles) => {
      console.log(roles);
      state.roles = roles;
    },
    SetSideBar: (state, sidebar) => {
      state.sidebar = sidebar;
    }
  },

  actions: {
    // 获取用户信息
    GetInfo({ commit }) {
      const token = localStorage.getItem("token");
      return new Promise((resolve, reject) => {
        serve
          .getLoginPermission({ Authorization: token })
          .then(response => {
            if (response.code !== 200) {
              Vue.prototype.$message.error("登录失效");
              // 登录验证 9006登录失效，跳回登录页面
              store.commit("SET_ROLES", []);
              localStorage.removeItem("token");
              localStorage.removeItem("tags");
              setTimeout(() => {
                window.location.reload();
              }, 500);
              reject();
              return;
            }
            localStorage.setItem("userName", response.data.name);
            const data = response.data.permissionTreeVO.rows;
            commit("SET_ROLES", [response.data.name]);
            store.commit("roleName", response.data.roleName);
            resolve(data);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    SetSideBar({ commit }, sidebar) {
      commit("SetSideBar", sidebar);
    }
  }
};

export default user;
